<template>
  <div>
    <div
      v-if="
        resourceSet.includes('/web/data-statistic/fund-statistic/总资金统计')
      "
      v-loading="datacardLoading"
      class="datacard-search-wrapper"
    >
      <div class="panel">
        <div class="panel-header">总资金统计</div>
        <div class="form-wrapper">
          <div class="form-content">
            <i-form
              class="iform"
              :layoutSpan="layoutSpan"
              :labelWidth="labelWidth"
              :breakpoint="breakpoint"
              :inline="true"
              :items="queryFormItems"
              :form="queryForm"
              :rules="queryFormRules"
            >
              <template slot="date">
                <el-form-item prop="date">
                  <SearchDatePicker
                    type="month"
                    :start.sync="queryForm.startTime"
                    :end.sync="queryForm.endTime"
                    :disable-date="disableDate"
                  />
                </el-form-item>
              </template>
              <template slot="address">
                <el-form-item>
                  <HycAddressCascader
                    v-model="queryForm.area"
                    :level="0"
                    :clearable="true"
                    size="small"
                  />
                </el-form-item>
              </template>
              <template slot="merchant" v-if="queryForm.containSubMch">
                <el-form-item>
                  <SearchMerchants
                    v-model="queryForm.mchUserId"
                    :defaultOptions="false"
                    size="small"
                  />
                </el-form-item>
              </template>
            </i-form>
            <div class="btn-wrapper">
              <el-button type="primary" size="small" @click="initDataCard">
                查询
              </el-button>
              <el-button size="small" @click="reset">重置</el-button>
            </div>
          </div>
        </div>
      </div>
      <data-card
        :data="dataCard"
        :items="dataCardItems"
        :tips="tips"
        @handleChange="initDataCard"
      />
    </div>
    <EchartPanel
      v-loading="dailyFundLoading"
      v-if="
        resourceSet.includes('/web/data-statistic/fund-statistic/每日流水统计')
      "
      :title="dailyFund"
      :formItemsInline="formItems"
      :timeUnit="'date'"
      @handleTableData="handleDailyFund"
      :echartsOption="lineBarOption"
    >
      <template slot="custUnitPrice">
        <el-form-item prop="custUnitPrice">
          <Tips :tips="unitPriceTips" class="unit-price__tips">
            <div>客单价：{{ custUnitPrice || 0 }}元</div>
          </Tips>
        </el-form-item>
      </template>
    </EchartPanel>
    <EchartPanel
      v-loading="monthlyFundLoading"
      v-if="
        resourceSet.includes('/web/data-statistic/fund-statistic/每月收入统计')
      "
      :title="monthlyFund"
      :timeUnit="'month'"
      @handleTableData="handleMonthlyFund"
      :echartsOption="lineBarOption"
    />
    <EchartPanel
      v-loading="profitLoading"
      v-if="
        resourceSet.includes('/web/data-statistic/fund-statistic/每日盈亏统计')
      "
      :title="profit"
      :timeUnit="'date'"
      @handleTableData="handleProfit"
      :echartsOption="barOption"
    />
  </div>
</template>
<script>
import dayjs from 'dayjs'
import HycAddressCascader from '@/components/hycAddressCascader'
import SearchMerchants from '@/components/SearchMerchants'
import EchartPanel from '@/components/EchartPanel'
import DataCard from './components/DataCard'
import Tips from './components/Tips'
import * as visualizationFun from '@/utils/visualizationFun'
import { constValue } from '@/config/echartsStyle'
import {
  getTotalFundStatistic,
  getDailyFundStatistic,
  getMonthlyFundStatistic,
  getDailyProfitStatistic,
} from '@/api/statistics'
import { barOption } from './data/device'
import { lineBarOption } from './data/fund'
export default {
  name: 'StatisticsFund',
  components: {
    HycAddressCascader,
    SearchMerchants,
    EchartPanel,
    DataCard,
    Tips,
  },
  data() {
    return {
      layoutSpan: 24,
      labelWidth: 20,
      breakpoint: [
        [768, 1],
        [992, 2],
        [1200, 2],
        [1920, 3],
        [Infinity, 4],
      ],
      queryForm: {
        containSubMch: true,
        mchUserId: '',
        startTime: null,
        endTime: null,
        area: {},
      },
      queryFormItems: [
        {
          slot: 'date',
        },
        {
          slot: 'address',
        },
        {
          slot: 'merchant',
        },
      ],
      disableDate: {
        startTime: dayjs('2024-01-01').valueOf(),
        endTime: dayjs().endOf('month').valueOf(),
      },
      queryFormRules: {
        date: [
          {
            validator: (rule, value, callback) => {
              if (this.queryForm.startTime && !this.queryForm.endTime) {
                callback(new Error('请选择结束时间'))
                return false
              }
              if (!this.queryForm.startTime && this.queryForm.endTime) {
                callback(new Error('请选择开始时间'))
                return false
              }
              callback()
            },
          },
        ],
      },
      datacardLoading: false,
      dailyFundLoading: false,
      monthlyFundLoading: false,
      profitLoading: false,
      dailyFund: '每日流水统计',
      monthlyFund: '每月流水统计',
      profit: '每日盈亏统计',
      custUnitPrice: '',
      visible: false,
      unitPriceTips: [
        '客单价=临充收入/付费订单',
        '付费订单=该日期内全部订单-套餐抵扣的订单-',
        '异常订单',
      ],
      tips: [
        '数据统计截止前一天',
        // '数据统计包含自营及下级代理资金',
        '总资金流水： 时长卡套餐流水+临充流水',
        '临充资金流水：临充收入+服务费流水-临充退款',
        '时长卡资金流水：时长卡套餐收入',
        // '和能量资金流水：和能量套餐收入-和能量套餐退款',
      ],
      dataCard: {
        totalFund: 0,
        paymentSum: 0,
        timeCardSum: 0,
      },
      dataCardItems: [
        {
          label: '总资金流水',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return Number(data.totalFund).toLocaleString('zh-CN', {
              maximumFractionDigits: 2,
            })
          },
        },
        {
          label: '临充资金流水',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return Number(data.paymentSum).toLocaleString('zh-CN', {
              maximumFractionDigits: 2,
            })
          },
        },
        {
          label: '时长卡资金流水',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return Number(data.timeCardSum).toLocaleString('zh-CN', {
              maximumFractionDigits: 2,
            })
          },
        },
        // {
        //   label: '和能量资金流水',
        //   symbol: '￥',
        //   unit: '元',
        //   formatter: (data) => {
        //     return (
        //       data.andEnergySum &&
        //       Number(data.andEnergySum.toFixed(2)).toLocaleString()
        //     )
        //   },
        // }, //todo
      ],
      lineBarOption: lineBarOption,
      barOption: barOption,
      formItems: [
        {
          slot: 'custUnitPrice',
        },
      ],
    }
  },
  computed: {
    resourceSet() {
      return this.$store.getters.resourceSet
    },
  },
  created() {
    this.initDataCard()
  },
  methods: {
    reset() {
      this.queryForm = {
        containSubMch: true,
        startTime: null,
        endTime: null,
        area: {},
        mchUserId: '',
      }
    },
    initDataCard() {
      this.datacardLoading = true
      const { containSubMch, mchUserId, startTime, endTime, area } =
        this.queryForm
      const params = {
        containSubMch,
        ...(mchUserId && { mchUserId }),
        ...(startTime && { startTime }),
        ...(endTime && { endTime }),
        ...(area && { province: area.province }),
      }
      getTotalFundStatistic(params).then(
        (res) => {
          this.dataCard = res
          this.datacardLoading = false
        },
        () => {
          this.datacardLoading = false
        }
      )
    },
    handleClose() {
      this.visible = !this.visible
    },
    handleDailyFund(params, instance) {
      this.dailyFundLoading = true
      getDailyFundStatistic(params).then(
        (res) => {
          this.dailyFundLoading = false
          this.custUnitPrice = res.custUnitPrice
          let dailyFundXAxis = []
          let totalFund = []
          let paymentSum = []
          let timeCardSum = []
          let andEnergySum = []
          let serviceSum = []
          res.eachFundStatisticList &&
            res.eachFundStatisticList.forEach((item) => {
              dailyFundXAxis.push(item.statisticsDate)
              totalFund.push(item.totalFund)
              paymentSum.push(item.paymentSum)
              timeCardSum.push(item.timeCardSum)
              andEnergySum.push(item.andEnergySum)
              serviceSum.push(item.serviceSum)
            })
          visualizationFun.getXAxis(dailyFundXAxis)
          let totalFundMax = visualizationFun.getMax(totalFund)

          instance.setOption({
            animation: true,
            xAxis: {
              data: dailyFundXAxis,
              show: true,
            },
            yAxis: [
              {
                name: '每日资金流水（元）',
                max: totalFundMax,
                show: true,
                nameTextStyle: {
                  padding: [100, 0, 0, 100],
                },
                interval: totalFundMax / constValue.splitNumber,
              },
            ],
            series: [
              {
                data: totalFund,
              },
              {
                data: paymentSum,
              },
              {
                data: timeCardSum,
              },
              {
                data: andEnergySum,
              },
              {
                data: serviceSum,
              },
            ],
          })
        },
        () => {
          this.dailyFundLoading = false
        }
      )
    },
    handleMonthlyFund(params, instance) {
      this.monthlyFundLoading = true
      getMonthlyFundStatistic(params).then(
        (res) => {
          this.monthlyFundLoading = false
          let monthlyFundXAxis = []
          let totalFund = []
          let paymentSum = []
          let timeCardSum = []
          let andEnergySum = []
          let serviceSum = []
          res.forEach((item) => {
            monthlyFundXAxis.push(item.statisticsDate)
            totalFund.push(item.totalFund)
            paymentSum.push(item.paymentSum)
            timeCardSum.push(item.timeCardSum)
            andEnergySum.push(item.andEnergySum)
            serviceSum.push(item.serviceSum)
          })
          visualizationFun.getMonthXAxis(monthlyFundXAxis)
          let totalFundMax = visualizationFun.getMax(totalFund)

          instance.setOption({
            animation: true,
            xAxis: {
              data: monthlyFundXAxis,
              show: true,
            },
            yAxis: [
              {
                name: '每月资金流水（元）',
                max: totalFundMax,
                show: true,
                nameTextStyle: {
                  padding: [100, 0, 0, 100],
                },
                interval: totalFundMax / constValue.splitNumber,
              },
            ],
            series: [
              {
                data: totalFund,
              },
              {
                data: paymentSum,
              },
              {
                data: timeCardSum,
              },
              {
                data: andEnergySum,
              },
              {
                data: serviceSum,
              },
            ],
          })
        },
        () => {
          this.monthlyFundLoading = false
        }
      )
    },
    handleProfit(params, instance) {
      this.profitLoading = true
      getDailyProfitStatistic(params).then(
        (res) => {
          this.profitLoading = false
          let profitXAxis = []
          let profit = []
          res.forEach((item) => {
            profitXAxis.push(item.statisticsDate)
            profit.push(item.profit)
          })
          visualizationFun.getXAxis(profitXAxis)
          let profitMax = visualizationFun.getMax(profit)
          instance.setOption({
            xAxis: {
              data: profitXAxis,
              show: true,
            },
            yAxis: [
              {
                name: '每日盈亏统计（元）',
                show: true,
                max: profitMax,
                min: function (value) {
                  return value.min < 0 ? -profitMax : 0
                },
                interval: profitMax / constValue.splitNumber,
                nameTextStyle: {
                  padding: [100, 0, 0, 100],
                },
              },
            ],
            series: [
              {
                name: '每日盈亏',
                type: 'bar',
                data: profit,
              },
            ],
            animation: true,
          })
        },
        () => {
          this.profitLoading = false
        }
      )
    },
  },
}
</script>
<style lang="scss" scoped>
.unit-price__tips {
  display: flex;
  align-items: center;
  &::v-deep .help-icon {
    margin-left: 10px;
    margin-top: -4px;
    vertical-align: middle;
  }
}
.datacard-search-wrapper {
  .form-wrapper {
    background: #fff;
    .form-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-left: -12px;
    }
    .iform {
      flex: 1;
      margin-left: 16px;
      margin-top: -5px;
    }
    .btn-wrapper {
      min-width: 130px;
      margin: 0 24px;
      .dash-control {
        cursor: pointer;
        margin: 0 5px;
        display: inline-block;
      }
    }
  }
  .data-card {
    margin: 40px 0 40px;
  }
}
</style>
